<template>
    <div class='edit-popup'>
        <popup
            ref='popupRef'
            :title='popupTitle'
            :async='true'
            width='680px'
            @confirm='handleSubmit'
            @close='handleClose'
        >
            <el-form label-position='left' ref='formRef' :model='formData' label-width='80px' :rules='formRules'>
                <el-form-item label='景点名称' prop='name'>
                    <el-input v-model='formData.name' clearable placeholder='请输入景点名称' />
                </el-form-item>
                <el-form-item label='城市' prop='city_id'>
                    <el-cascader
                        style='width:280px;'
                        v-model='formData.city_id'
                        :options='cityData'
                    />
                </el-form-item>
                <el-form-item label='景点地址' prop='addr'>
                    <el-input v-model='formData.addr' clearable placeholder='请输入景点地址' />
                </el-form-item>
                <el-form-item label='经纬度' prop='location'>
                    <el-input v-model='formData.location' clearable
                              placeholder='请输入经纬度(直接将复制的经纬度粘贴到此处即可)'>
                        <template #append>
                            <el-button type='danger' @click='getLocation'>获取坐标</el-button>
                        </template>
                    </el-input>
                </el-form-item>
<!--                <el-form-item :label='`景点${index + 1}`' v-for='(item,index) in pointKeys' :key='index' :prop='item'>-->
<!--                    <div style='width: 100%;display:flex;flex-flow:row nowrap;gap: 24px;'>-->
<!--                        <div>-->
<!--                            <el-date-picker-->
<!--                                v-model='formData[item].time'-->
<!--                                type='datetime'-->
<!--                                placeholder='请选择游玩日期、时间'-->
<!--                                value-format='YYYY-MM-DD hh-mm'-->
<!--                            />-->
<!--                        </div>-->
<!--                        <div style='flex: 1;'>-->
<!--                            <el-input v-model='formData[item].name' clearable placeholder='请输入景点' />-->
<!--                        </div>-->
<!--                        <el-button @click='removePoint(item)' type='danger' :icon='Delete' circle />-->
<!--                    </div>-->
<!--                </el-form-item>-->
            </el-form>
<!--            <div class='pop-footer'>-->
<!--                <el-button @click='addPoint(false)' style='width: 100%' type='primary' plain>添加景点</el-button>-->
<!--            </div>-->
        </popup>
    </div>
</template>

<script lang='ts' setup name='lineSpotEdit'>
import { CloseBold } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiLineSpotAdd, apiLineSpotEdit, apiLineSpotDetail } from '@/api/line_spot'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import { ElMessage } from 'element-plus/es'
import { computed } from 'vue'
import { getCity, getCityNew } from '@/api/article'
import { Delete } from '@element-plus/icons-vue'

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')


function removePoint(key: string) {
    delete formData[key]
    delete formRules[key]
}

function addPoint(value: any) {
    if (!value) value = { time: '', name: '' }
    const len = pointKeys.value.length
    const key = 'points_' + len
    formData[key] = value
    formRules[key] = getPointValidator()
}

const pointKeys = computed(() => {
    const keys = Object.keys(formData)
    return keys.filter(item => item.includes('points'))
})

function getPoints() {
    return pointKeys.value.map(item => {
        return formData[item]
    })
}

function getPointValidator() {
    return [
        {
            trigger: 'change',
            validator: (_: any, value: any, callback: any) => {
                const { time, name } = value
                if (!time) return callback(new Error('请选择时间'))
                if (!name) return callback(new Error('请输入名称'))
                callback()
            }
        }
    ]
}

const timeOption = computed(() => {
    const patchZero = (value: number) => {
        return ('0' + value).slice(-2)
    }
    const result = []
    for (let i = 0; i < 24; i++) {
        const label = patchZero(i) + ':00'
        result.push({
            label,
            value: label
        })
    }
    return result
})
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑景点管理' : '新增景点管理'
})

// 表单数据
const formData = reactive({
    id: '',
    name: '',
    value: '',
    points_0: { time: '', name: '' },
    city_id: [],
    location: '',
    addr: ''
})
const cityData = ref([])

function getLocation() {
    window.open('https://lbs.qq.com/getPoint/')
}

initCityData()

async function initCityData() {
    const resp = await getCityNew({})
    if (!resp || !resp.length) return

    function patchMap(v: any) {
        if (!v.hasOwnProperty('children')) return
        if (!v.children || !v.children.length) return
        return v.children.map((item: any) => {
            const { id, name } = item
            const data = {
                value: id, label: name
            }
            const children = patchMap(item)
            if (children) data.children = children
            return data
        })
    }

    cityData.value = resp.map((item: any) => {
        const { id, name, children } = item
        return {
            label: name, value: id, children: patchMap(item)
        }
    })
}

// 表单验证
const formRules = reactive<any>({
    name: [
        {
            required: true,
            message: '请输入景点名称',
            trigger: 'blur'
        }
    ],
    city_id: [
        {
            required: true,
            message: '请选择对应城市',
            trigger: 'blur'
        }
    ],
    addr: [
        {
            required: true,
            message: '请输入景点地址',
            trigger: 'blur'
        }
    ],
    location: [
        {
            required: true,
            message: '请输入经纬度',
            trigger: 'blur'
        },
        {
            validator: (rules: any, value: string, callback: any) => {
                if (!value) return callback(new Error('请输入经纬度'))
                const locationArr = value.split(',')
                if (!locationArr || !Array.isArray(locationArr) || locationArr.length !== 2) return callback(new Error('经纬度使用英文输入法的逗号分隔'))
                const [lng, lat] = locationArr
                if (!lng || !lat) return callback(new Error('请输入合法的经纬度'))
                callback()
            },
            trigger: 'blur'
        }
    ]
})

function initSpotHandle(list: any[]) {
    // 先清除已填写的
    pointKeys.value.forEach(key => {
        removePoint(key)
    })
    if (!list || !list.length) return
    list.forEach((item) => addPoint(item))
}

// 获取详情
const setFormData = async (data: Record<any, any>) => {
    console.log(data, 'data')
    const { id, name, province, area, city_id, addr, lng, lat } = data
    formData.id = id
    formData.name = name
    formData.city_id = [province, city_id, area]
    formData.addr = addr
    formData.location = `${lng},${lat}`
    if (data.value && typeof data.value === 'string') {
        const list = JSON.parse(data.value)
        initSpotHandle(list)
    }
    // value.forEach((item: any, index: number) => {
    //     formData['points_' + index] = item
    // })
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiLineSpotDetail({
        id: row.id
    })
    setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const points = getPoints()
    const { id, name, city_id, addr, location } = formData
    const [lng, lat] = location.split(',')
    const data = {
        value: '', id, name, city_id, addr, lng, lat
    }
    mode.value == 'edit'
        ? await apiLineSpotEdit(data)
        : await apiLineSpotAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}


defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
<style scoped>
.pop-footer {
    margin-top: 24px;
}
</style>
